<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="审批详情" data-page-identification="u_j7266s2v66">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_2vi0nij9ww 自定义模板_z2dtdpmxqj -->
            <div v-if="loading" class="flex justify-center items-center h-60">
                <a-spin size="large" />
            </div>
            <div v-else>
                <template v-if="useType && useType !== 'PPM' && statuState.isShowZdh">
                    <div class="zdh-body">
                        <div class="html-content" v-html="statuState.reportHtml" v-if="statuState.reportHtml"></div>
                        <a-empty v-else />
                        <div class="tip">反馈结果调整</div>
                        <a-form-item label="提示词编辑">
                            <a-textarea v-model:value="statuState.verifyCueWord" />
                        </a-form-item>

                    </div>
                </template>
                <template v-else>
                    <div class="status-item" v-for="(item, index) in statuState.list">
                        <div class="title-new-status">
                            <div class="left-title"
                                >审批类型:<span class="weight-status-new">{{ item.processName }} </span></div
                            >
                            <div class="right-title"
                                >审批提交时间:<span class="weight-status-new">{{ item.createdDate }} </span></div
                            >
                        </div>
                        <a-steps class="status-step" direction="vertical">
                            <a-step
                                v-for="(inside, index) in item.processTaskList"
                                :key="index"
                                :status="getIconStatus(inside.nodeStatus)"
                            >
                                <template #title>
                                    <div
                                        style="display: flex; justify-content: space-between; align-items: center"
                                        class="step-btn-body"
                                    >
                                        <span>{{ inside.nodeMessage }}</span>
                                        <!--  v-if="inside.nodeMessage.includes('自动化')"-->
                                        <!--                              v-if="useType !== 'PPM' && item.processName.includes('完成任务')"-->
                                    </div>
                                </template>

                                <template #description> {{ inside.taskName }} : {{ inside.assignUserName }} </template>
                            </a-step>
                        </a-steps>
                    </div>
                </template>
            </div>
            <!-- end vid_2vi0nij9ww 自定义模板_z2dtdpmxqj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'source': {
            type: [String],
            default: undefined
        },
        'taskId': {
            type: [String, Number],
            default: undefined
        },
        'type': {
            type: [String, Number],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const { taskId, source, type } = props
    const useTaskId = ref()
    const useSource = ref()
    const useType = ref()
    const loading = ref(false)
    import { watchEffect } from 'vue'
    watch(
        () => props.taskId,
        newVal => {
            if (newVal) {
                useTaskId.value = newVal
                useSource.value = props.source
                useType.value = props.type
                getData()
            }
        },
        { immediate: true }
    )

    const statuState = reactive({
        visible: false,
        list: [],
        largeModelVisible: false,
        verifyCueWord: undefined,
        reportHtml: undefined,
        isShowZdh: true
    })

    function getData() {
        loading.value = true
        if (useType.value !== 'PPM') {
            get(`/solution-ppm/api/v2/built-in-system-ppm/third_task/task_result/${useTaskId.value}`)
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        statuState.isShowZdh = false
                        return
                    }
                    statuState.isShowZdh = true
                    statuState.visible = true
                    let html = stripMdFence(data.data.htmlJson)
                    console.log(html, 'html')
                    statuState.reportHtml = html
                    statuState.verifyCueWord = data.data.verifyCueWord
                })
                .finally(() => {
                    loading.value = false
                })
        } else {
            get(
                `/solution-ppm/api/v2/built-in-system-ppm/refactoring_task/task_approval_detail/${useTaskId.value}/${useSource.value}    `
            )
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    statuState.visible = true
                    statuState.list = data.data
                })
                .finally(() => {
                    loading.value = false
                })
        }
    }
    function stripMdFence(str) {
        if (typeof str !== 'string') return ''
        // 1) 去掉 UTF-8 BOM
        let s = str.replace(/^\uFEFF/, '')
        // 2) 去掉开头代码围栏（允许前导空白、``` 或 ~~~、可选语言、可选空白+换行）
        s = s.replace(/^\s*(?:```|~~~)+[^\n\r]*\s*\r?\n/, '')
        // 3) 去掉结尾代码围栏（到文本末尾）
        s = s.replace(/\r?\n?(?:```|~~~)+\s*$/, '')
        return s
    }

    const getIconStatus = status => {
        if (status === 'finish') {
            return 'finish'
        } else if (status === 'process') {
            return 'process'
        } else {
            return 'error'
        }
    }
    // 这里返回 Promise，供父组件 await
    async function submitWord() {
        if (!statuState.verifyCueWord) {
            message.info('请输入提示词')
            return Promise.reject(new Error('请输入提示词'))
        }
        try {
            const data = await post('/solution-ppm/api/v2/built-in-system-ppm/third_task/task_result/regenerate', {
                taskId: useTaskId.value,
                cueWord: statuState.verifyCueWord
            })
            if (data.code !== 200) {
                message.error(data.message)
                return Promise.reject(new Error(data.message))
            }
            message.success('提交成功，请稍后查看详情')
            emit('cancelModel')
            emit('refechData')
            return Promise.resolve(true)
        } finally {
        }
    }
    const emit = defineEmits(['cancelModel', 'refechData'])

    function handleCancelFatherModal() {
        emit('cancelModel') // 触发父组件方法
    }
    function handleRefechData() {
        emit('refechData') // 触发父组件方法
    }
    // 暴露给父组件
    defineExpose({
        submitWord
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/

    .title-new-status {
        height: 62px;
        line-height: 36px;
        padding: 0 16px;
        margin-bottom: 16px;
        background-image: url('http://10.40.0.33:9001/file-storage/457843108093009920-source.png');
        background-size: cover;
        border: 1px solid #3875ff;
        border-radius: 5px;
    }

    :deep(.ant3-steps-item-container) {
        padding: 0 16px;
    }
    :deep(.ant3-steps-item-tail::after) {
        margin-left: 12px;
        background-color: #3875ff;
    }
    :deep(.ant3-steps-item-description) {
        font-size: 12px;
        color: #595959;
        text-align: left;
        line-height: 20px;
        font-weight: 400;
    }
    :deep(.ant3-steps-item-icon) {
        width: 24px;
        height: 24px;
        line-height: 24px;
        color: #3875ff;
        margin-top: 6px;
    }
    :deep(.ant3-steps-item-title) {
        height: 28px;
        font-size: 14px;
        color: #262626;
        text-align: left;
        line-height: 22px;
        font-weight: 400;
    }
    :deep(.ant3-steps-item-process > .ant3-steps-item-container > .ant3-steps-item-icon) {
        background-color: #3875ff;
    }
    :deep(.ant3-steps-vertical > .ant3-steps-item > .ant3-steps-item-container > .ant3-steps-item-tail::after) {
        background: #3875ff;
    }
    :deep(.status-step .ant3-steps-vertical > .ant3-steps-item .ant3-steps-item-icon) {
        border-color: #3875ff;
    }
    :deep(.ant3-steps-item-finish .ant3-steps-item-icon > .ant3-steps-icon) {
        color: #3875ff !important;
    }
    .task-status-new {
        cursor: pointer;
    }
    .left-title,
    .right-title {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        letter-spacing: 0;
        text-align: left;
        font-weight: 400;
        height: 31px;
        line-height: 31px;
    }
    .weight-status {
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 500;
    }
    .batch-line {
        width: 100%;
        border-top: 1px solid #d9d9d9;
        margin: 16px 0;
    }
    .weight-status-new {
        font-weight: 600;
        color: #262626;
    }
    .task-collaborate {
        width: 58px;
        text-align: center;
        height: 16px;
        line-height: 16px;
        position: absolute;
        top: 12px;
        left: 9px;
        background-color: #eee5fa;
        color: #9254de;
    }
    .task-name-title-right {
        margin-left: 80px;
    }
    .status-item {
        height: 100%;
    }
    .step-btn-body {
        position: relative;
    }
    .step-btn {
        position: absolute;
        right: -220px;
    }
    .tip {
        height: 14px;
        line-height: 14px;
        border-left: 4px solid #3875ff;
        padding-left: 4px;
        margin-bottom: 16px;
        margin-top: 16px;
    }
    .zdh-body {
        position: relative;
    }
    .bottom-btn {
        display: flex;
        justify-content: end;
    }
</style>
